package com.zq.多线程设计模式.workerThread设计模式;

// 产品传送带
public class ProductionChannel {

    private final static int MAX_PROD = 100;

    private final Production[] productionQueue;
    private int tail;
    private int head;
    private int totle;
    private final Worker[] workers;

    public ProductionChannel(int workerSize) {
        this.workers = new Worker[workerSize];
        this.productionQueue = new Production[MAX_PROD];

        // 实例化每一个工人（worker Thread） 并启动
        for (int i = 0; i < workerSize; i++) {
            workers[i] = new Worker("Worker-" + i, this);
            workers[i].start();
        }
    }

    public void offerProduction(Production production) {
        synchronized (this) {
            while (totle >= productionQueue.length) {
                try {
                    this.wait();
                } catch (InterruptedException e) {

                }
                productionQueue[tail] = production;
                tail = (tail + 1) % productionQueue.length;
                totle++;
                this.notifyAll();
            }
        }
    }

    public Production takeProduction() {
        synchronized (this) {
            while (totle <= 0) {
                try {
                    this.wait();
                } catch (InterruptedException e) {

                }
            }
            Production prod = productionQueue[head];
            head = (head + 1) % productionQueue.length;
            totle--;
            this.notifyAll();
            return prod;

        }
    }

}
